package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.BaseDTO;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exceptions.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import com.sun.corba.se.spi.orbutil.threadpool.WorkQueue;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private CategoryBrandService categoryBrandService;

    //根据分类id查询品牌
    @Override
    public List<BrandDTO> queryBrandByCategory(Long id) {
        //select brand_id from tb_category_brand where category_id=325
        List<CategoryBrand> categoryBrandList = categoryBrandService.query().eq("category_id", id).list();
        //获取结果中的brand_id
        List<Long> brandIds = categoryBrandList.stream()
                .map(categoryBrand -> categoryBrand.getBrandId())
                .collect(Collectors.toList());
        //select * from tb_brand where id in ()
        List<Brand> brandList = this.listByIds(brandIds);
        //转DTO
        return BrandDTO.convertEntityList(brandList);
    }

    //分页查询品牌
    @Override
    public PageDTO<BrandDTO> queryBrandByPage(String key, Integer page, Integer rows) {
        // 1.分页信息的健壮性处理
        page = Math.max(1, page);
        rows = Math.max(1, rows);

        // 3.判断key是否存在(是否在搜索框输入内容)
        boolean isKeyExists = StringUtils.isNotBlank(key);

        // 4.如果key存在，添加like和eq的查询条件，否则不添加
        //select * from tb_brand where name like '%小%' or letter = '%X%' limit 0,5 #letter商品名称首字母
        Page<Brand> brandPage = this.query()
                .like(isKeyExists,"name", key)
                .or()
                .eq(isKeyExists,"letter", key)
                .page(new Page<>(page, rows));

        //5.转换dto
        PageDTO<BrandDTO> brandDTOPageDTO = new PageDTO<>(brandPage.getTotal(), brandPage.getPages(), BrandDTO.convertEntityList(brandPage.getRecords()));
        return brandDTOPageDTO;
    }

    //新增品牌
    @Override
    @Transactional
    public void saveBrand(BrandDTO brandDTO) {
        //DTO转PO
        Brand brand = brandDTO.toEntity(Brand.class);
        //保存数据到品牌表
        boolean success = this.save(brand);
        if (!success){
            throw new LyException(500,"更新品牌失败");
        }
        //保存数据到中间表（分类品牌表）

        //获取品牌相关联的分类
        List<Long> categoryIds = brandDTO.getCategoryIds();

        //方式二  流
        List<CategoryBrand> categoryBrandList = categoryIds.stream()
                //静态方法of()的作用是 利用全参构造创建对象
                .map(categoryId -> CategoryBrand.of(categoryId, brand.getId()))
                .collect(Collectors.toList());

        /*//方式一  遍历保存到集合
        List<CategoryBrand> categoryBrandList = new ArrayList<>(categoryIds.size());
        for (Long categoryId : categoryIds) {
            //静态方法of()的作用是 利用全参构造创建对象
            CategoryBrand categoryBrand = CategoryBrand.of(categoryId, brand.getId());
            categoryBrandList.add(categoryBrand);
        }*/
        //批量保存到中间表
        categoryBrandService.saveBatch(categoryBrandList);
    }

    //更新品牌
    @Override
    @Transactional
    public void updateBrand(BrandDTO brandDTO) {
        //DTO转PO
        Brand brand = brandDTO.toEntity(Brand.class);
        //更新品牌表
        boolean success = this.updateById(brand);
        if (!success) {
            // 更新失败，抛出异常
            throw new LyException(500, "更新品牌失败！");
        }

        //更新中间表

        //1.先删除中间表维护的关系
        QueryWrapper<CategoryBrand> wrapper = new QueryWrapper<>();
        wrapper.eq("brand_id",brandDTO.getId());
        success = categoryBrandService.remove(wrapper);
        if (!success) {
            // 更新失败，抛出异常
            throw new LyException(500,"更新品牌失败，删除中间表数据出错");
        }

        //2.再添加新的关系到中间表

        //获取品牌相关联的分类
        List<Long> categoryIds = brandDTO.getCategoryIds();
        List<CategoryBrand> categoryBrandList = categoryIds.stream()
                //静态方法of()的作用是 利用全参构造创建对象
                .map(categoryId -> CategoryBrand.of(categoryId, brand.getId()))
                .collect(Collectors.toList());
        categoryBrandService.saveBatch(categoryBrandList);
    }

    //根据ID删除品牌
    @Override
    @Transactional
    public void deleteBrandById(Long id) {
        //删除中间表
        QueryWrapper<CategoryBrand> wrapper = new QueryWrapper<>();
        wrapper.eq("brand_id",id);
        categoryBrandService.remove(wrapper);
        //删除品牌表
        this.removeById(id);
    }
}
